package com.tchintech.pay.utils;

import java.io.File;
import java.io.StringReader;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

/**
 * 
 *
 * @version 1.0
 */
public class StringUtil {

	public static Uri getUriByFile(Context context, File File) {
		String tepmpoth = Uri.decode(File.getPath());
		ContentResolver cr = context.getContentResolver();
		StringBuffer buff = new StringBuffer();
		buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
				.append("'" + File.getPath() + "'").append(")");
		Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				new String[] { MediaStore.Images.ImageColumns._ID }, buff.toString(),
				null, null);
		int index = 0;
		if (cur.moveToFirst()) {
			index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
			index = cur.getInt(index);
		}
		Uri uri_temp = Uri.parse("content://media/external/images/media/"
				+ index);
		return uri_temp;
	}

	public static byte[] md5Byte(String encryptStr) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(encryptStr.getBytes("UTF-8"));
		return md.digest();
	}

	public static String convert(final byte bytes[],int pos, int len) {

		StringBuffer sb = new StringBuffer(len * 2);
		for (int i = pos; i < pos+len; i++) {
			sb.append(convertDigit((int) (bytes[i] >> 4)));
			sb.append(convertDigit((int) (bytes[i] & 0x0f)));
		}
		return (sb.toString());

	}
	public static char convertDigit(int value) {
		value &= 0x0f;
		if (value >= 10)
			return ((char) (value - 10 + 'a'));
		else
			return ((char) (value + '0'));
	}
	/**
	 * 验证用户名
	 * */
	public static boolean validate(String str) {
		Boolean flag = Pattern.matches("^\\d{6}$", str);
		return flag;
	}

	/**
	 * 邮件合法性判断
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isValidEmail(String email) {

		String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(email);
		return m.matches();

	}

	public static String stringToAscii(String value) {
		StringBuffer sbu = new StringBuffer();
		char[] chars = value.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if (i != chars.length - 1) {
				sbu.append((int) chars[i]).append(",");
			} else {
				sbu.append((int) chars[i]);
			}
		}
		return sbu.toString();
	}

	public static String asciiToString(String value) {
		StringBuffer sbu = new StringBuffer();
		String[] chars = value.split(",");
		for (int i = 0; i < chars.length; i++) {
			sbu.append((char) Integer.parseInt(chars[i]));
		}
		return sbu.toString();
	}

	/**
	 * 去掉字符串中没用的0
	 * 
	 * @param number
	 * @return
	 */
	public static String getPrettyNumber(String number) {
		return BigDecimal.valueOf(Double.parseDouble(number))
				.stripTrailingZeros().toPlainString();
	}

	public static int getIntNumber(int code) {
		String len = String.valueOf(code);
		return len.length();
	}

	public static boolean isNotEmpty(String str) {
		if ((str == null) || str.equals("") || str.equalsIgnoreCase("null")) {
			return false;
		}
		return true;
	}

	public static int isNotEmptyForInt(String str) {
		if ((str == null) || str.equals("") || str.equalsIgnoreCase("null")) {
			return 0;
		}
		return 1;
	}
	public static boolean isNotEmpty(EditText edit) {
		String str = edit.getText().toString();
		if (isNotEmpty(str)) {
			return true;
		} else {
			//edit.setError("该输入框内容不能为空！");
			edit.requestFocus(); // 增加焦点才有错误提示文字
			edit.setFocusable(true);
			return false;
		}
	}

	public static int setAdpterByHpzl(String hpzl) {
		int type = -1;
		if (hpzl.equals("01")) {
			type = 1;
		} else if (hpzl.equals("02")) {
			type = 2;
		}
		return type;
	}
	
	public static String[] getStrings(String data){
		String [] sts = new String[]{};
		sts = data.split("|");
		
		return sts;
		
	}
	
	/**
	 * @描述: 获取符号第n次出现的位置
	 * @参数: @return
	 * @返回值: int
	 */
	public static int getCharacterPosition(String string,int size) {
		// 这里是获取"/"符号的位置
		// http://192.168.0.229:8080/GYKFOA/attachFiles/document/privateDocument/201506/4d46bdf62a0b417992001e2745c7def5.xlsx
		Matcher slashMatcher = Pattern.compile("/").matcher(string);
		int mIdx = 0;
		while (slashMatcher.find()) {
			mIdx++;
			// 当"/"符号第n次出现的位置
			if (mIdx == size) {
				break;
			}
		}
		return slashMatcher.start();
	}

	public static String object2json(Object o ){
		Gson gson = new Gson();
		return gson.toJson(o);
	}

	public static String toString(Object obj) {
		if( obj == null ){
			return "";
		}
		return toString(obj, "utf-8");
	}
	public static String toString(Object obj, String charset) {
		if (obj instanceof byte[]) {
			try {
				return new String((byte[]) obj, charset);
			} catch (Exception e) {
				return new String((byte[]) obj);
			}
		} else {
			return obj.toString();
		}
	}


	/**
	 * 结果集转List
	 * @param result
	 * @param classOfT
     * @return
     */
	public static List result2List(String result,Class classOfT){

		result=result.replace("[]","\"\"");
		result=result.replace("\\n","");//去除body返回为\n 的情况.
		JsonReader reader = new JsonReader(new StringReader(result));
		reader.setLenient(true);
		JsonElement jsonElement = new JsonParser().parse(result);
		jsonElement = jsonElement.getAsJsonObject().get("body");
		List ls;
		if (!jsonElement.toString().equals("\"\"")) {//如果body无值 就不处理.
			try {
				JsonArray body = jsonElement.getAsJsonArray();
				//Result rr = gson.fromJson(result, Result.class);
				 ls = new ArrayList();
				Iterator it = body.iterator();
				while (it.hasNext()) {  //循环
					jsonElement = (JsonElement) it.next(); //提取JsonElement
					Gson gson = new Gson();
					Object object = gson.fromJson(jsonElement, classOfT); //String转化成JavaBean
					ls.add(object);  //加入List
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				return null;
			}
			return ls;
		}else{
			return null;
		}

	}
}
